import Request from '@/utils/luch-request/index.js'
import Store from "@/store/store.js"



const api = new Request()
// export {
// 	api
// }

api.setConfig((config) => {
	console.log('Store',Store.state.shopUserInfo);
	/* config 为默认全局配置*/
	config.baseURL = Store.state.shopHttpAPI
	config.header = {
		'X-Requested-With': 'XMLHttpRequest',
		"Accept": "application/json",
		'Authorization': (Store.state.shopUserInfo && Store.state.shopUserInfo.token) ?  ('Bearer' + ' ' + Store.state.shopUserInfo.token) : '',
		"Content-Type": "application/json; charset=UTF-8"
	}
	return config
})
//请求前拦截
api.interceptors.request.use((config) => { // 可使用async await 做异步操作
// console.log('请求前拦截',config);
  let Store = getApp().globalData.store
   // console.log(Store.state,'Store.state.Store.state.')
	config.header = {
		...config.header,
		Authorization: (Store.state.shopUserInfo && Store.state.shopUserInfo.token) ?  ('Bearer' + ' ' + Store.state.shopUserInfo.token) : '',
	}
	config.params = {
		format: 'json',
		ts: Date.parse(new Date()),
		...config.params

	}
	//获取存储的token
	// const token = uni.getStorageSync('token');
	// config.header.token = token;
	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})


// 请求后拦截器
api.interceptors.response.use((response) => {
	if(response.data.code == 10040){
		const jump = uni.getStorageSync('jump')
		if(!jump){
			setTimeout(()=>{
				uni.showToast({
					title:response.data.msg,
					icon:'none',
					success:res=>{
						// 返回上一页
						uni.redirectTo({
							url:'/pages/my/children/login',
							success:res=> {
								// 清空本地存储的登录数据
								this.$store.commit('setShopInfo', {});
								uni.setStorageSync('mem-username', '')
								uni.setStorageSync('mem-password', '')
								uni.setStorageSync('sms-mobile', '')
								this.$store.commit('setInit', {});
								this.$store.commit('setLoginInfo', {});
								this.$store.commit('setUserInfo', {});
								uni.setStorageSync('mem-openid','')
								this.$store.commit('setSelectedGame','')
							}
						})
					}
				})
			},300)
			uni.setStorageSync('jump',true)
		}
	}
	// console.log('请求后拦截器',response);
	return response
}, (response) => {
	//未登录时清空缓存跳转
	// if(response.statusCode ==401){
	//  uni.clearStorageSync();
	//  uni.navigateTo({
	//  	url:"/pages/login/wechat"
	//  })
	// }
	return Promise.reject(response)
})

const $shopApi = {
	get(url, data) {
		return api.get(url, {
			params: data
		});
	},
	post(url, data) {
		return api.post(url, data);
	},
	put(url, data) {
		return api.put(url, data);
	}
}

export {
	$shopApi
}
